package com.sailing.xjpb.web.base.corsfilter.configration;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Collections;
import java.util.List;

/**
 * 网关相关配置
 *
 * @author YW
 */
@Data
@Configuration
@ConfigurationProperties(prefix = "xjpb.web.corsfilter")
public class CorsFilterConfig {
    /**
     * 跨域拦截的url
     */
    private String filterUrl = "/**";
    /**
     * 1允许任何域名使用
     */
    private List<String> allowedOrigins = Collections.singletonList("*");
    /**
     * 2允许任何头
     */
    private List<String> allowedHeaders = Collections.singletonList("*");
    /**
     * 3允许任何方法（post、get等）
     */
    private List<String> allowedMethods = Collections.singletonList("*");
    /**
     * 是否支持跨域用户凭证
     */
    private boolean allowCredentials = false;
    /**
     * 跨域过滤器的执行顺序
     */
    private int filterOrder = Ordered.HIGHEST_PRECEDENCE;

    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowedOrigins(allowedOrigins);
        corsConfiguration.setAllowedHeaders(allowedHeaders);
        corsConfiguration.setAllowedMethods(allowedMethods);
        if (allowCredentials) {
            corsConfiguration.setAllowCredentials(true);
        }
        return corsConfiguration;
    }


    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(source));
        bean.setOrder(filterOrder);
        return bean;
    }
}